from pymongo import MongoClient, DESCENDING
from func import Func


class MyMongoClient:
    def __init__(self, host, port, server_port, ip, *args,
                 **kwargs):
        #  标志 D J A 区分
        self.client = MongoClient(host=host, port=int(port))

        # self.card = self.client.guidang4.card
        self.cardacvs = self.client.guidang4.cardacvs
        self.faceacvs = self.client.guidang4.faceacvs
        # self.cardface = self.client.guidang4.cardface
        # self.acvs = self.client.guidang4.acvs

        self.config = self.client.guidang4config.config

        self.ip = ip
        self.server_port = server_port

        self.config_D = self.config.find_one({'_id': '%s_%s_D' % (self.ip, self.server_port)})
        self.config_J = self.config.find_one({'_id': '%s_%s_J' % (self.ip, self.server_port)})
        self.config_A = self.config.find_one({'_id': '%s_%s_A' % (self.ip, self.server_port)})

        self.box_ip_D = self.config_D.get('h_ip')
        self.box_ip_J = self.config_J.get('h_ip')
        self.box_ip_A = self.config_A.get('h_ip')

        self.box_port_D = self.config_D.get('h_port')
        self.box_port_J = self.config_J.get('h_port')
        self.box_port_A = self.config_A.get('h_port')

        self.box_uname_D = self.config_D.get('h_uname')
        self.box_uname_J = self.config_J.get('h_uname')
        self.box_uname_A = self.config_A.get('h_uname')

        self.box_upassword_D = self.config_D.get('h_pwd')
        self.box_upassword_J = self.config_J.get('h_pwd')
        self.box_upassword_A = self.config_A.get('h_pwd')

        self.func_client_D = Func(self.box_ip_D, self.box_port_D, self.box_uname_D, self.box_upassword_D)
        self.func_client_J = Func(self.box_ip_J, self.box_port_J, self.box_uname_J, self.box_upassword_J)
        self.func_client_A = Func(self.box_ip_A, self.box_port_A, self.box_uname_A, self.box_upassword_A)

    def get_cardacvs(self, card_info, card_p_list):
        card_img = list(self.cardacvs.find(card_info))
        for card_img_one in card_img:
            if card_img_one.get("level") > 2:
                continue
            data = {
                "acvs_id": card_img_one.get("acvs_id"),
                "name": card_img_one.get("name"),
                "person_id": card_img_one.get("person_id"),
                "similarity": card_img_one.get("similarity_average"),
                "count": card_img_one.get("count")
            }
            card_p_list.append(data)

        return card_p_list

    def get_faceacvs(self, face_info, stranger_p_list):
        face_img = list(self.faceacvs.find(face_info).sort("timestamp", DESCENDING).limit(5000))
        for face_img_one in face_img:
            data = {"acvs_id": face_img_one.get("acvs_id")}
            if data not in stranger_p_list:
                stranger_p_list.append(data)

        return stranger_p_list
